package com.sa.token.exception;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.sa.token.message.StandardResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;

/**
 * @desc: 全局异常处理
 * @author: xhs
 * @date: 2021/8/19 13:32
 * @version: JDK 1.8
 */
@Slf4j
@ControllerAdvice
public class GlobalException {

    /**
     * 在当前类每个方法进入之前触发的操作
     *
     * @param request
     * @throws IOException
     */
    @ModelAttribute
    public void get(HttpServletRequest request) throws IOException {
    }

    /**
     * 参数校验的异常(post)
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public StandardResponse methodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.error("参数校验失败(POST):{}", fieldError.getDefaultMessage());
        return StandardResponse.error(400, fieldError.getDefaultMessage());
    }

    /**
     * 参数校验的异常(get)
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public StandardResponse constraintViolationException(HttpServletRequest request, ConstraintViolationException ex) {
        log.error("参数校验失败(GET):{}", ex.getMessage());
        return StandardResponse.error(400, ex.getMessage());
    }

    /**
     * 全局异常拦截（拦截项目中的所有异常）
     *
     * @param e
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @ExceptionHandler
    public StandardResponse handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 如果是未登录异常
        if (e instanceof NotLoginException) {
            NotLoginException ee = (NotLoginException) e;
            log.error("全局异常:{}---------------", ee.getMessage());
            return StandardResponse.error(500, ee.getMessage());
        }
        // 如果是角色异常
        if (e instanceof NotRoleException) {
            NotRoleException ee = (NotRoleException) e;
            log.error("角色异常:{}---------------", ee.getMessage());
            return StandardResponse.error(901, ee.getMessage());
        }
        // 如果是权限异常
        if (e instanceof NotPermissionException) {
            NotPermissionException ee = (NotPermissionException) e;
            log.error("权限异常:{}---------------", ee.getMessage());
            return StandardResponse.error(902, ee.getMessage());
        }
        // 如果是被封禁异常
        if (e instanceof DisableLoginException) {
            DisableLoginException ee = (DisableLoginException) e;
            log.error("账号异常:{}---------------", ee.getMessage());
            return StandardResponse.error(903, "账号被封禁：" + ee.getDisableTime() + "秒后解封");
        } else {    // 普通异常, 输出：500 + 异常信息
            log.error("全局异常1:{}---------------", e.getMessage());
            return StandardResponse.error(500, e.getMessage());
        }
    }


    /**
     * 全局异常拦截（拦截项目中的NotLoginException异常）
     *
     * @param nle
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @ExceptionHandler(NotLoginException.class)
    public StandardResponse handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 判断场景值，定制化异常信息
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            log.error("---------------NotLoginException异常:未提供token---------------");
            return StandardResponse.error(401, "未提供token");
        }
        if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            log.error("---------------NotLoginException异常:token无效---------------");
            return StandardResponse.error(401, "token无效");
        }
        if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            log.error("---------------NotLoginException异常:token已过期---------------");
            return StandardResponse.error(401, "token已过期");
        }
        if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            log.error("---------------NotLoginException异常:token已被顶下线---------------");
            return StandardResponse.error(905, "账号已在其他地方登录");
        }
        if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            log.error("---------------NotLoginException异常:token已被踢下线---------------");
            return StandardResponse.error(905, "token已被踢下线");
        } else {
            return StandardResponse.error(906, "未登录");
        }
    }
}
